#include "proc/uptime.h"


void uptime_print(Uptime *uptime) {
    printf("day: %d, hour: %d, min: %d, sec: %d\n", 
            uptime->day, 
            uptime->hour, 
            uptime->min, 
            uptime->sec);
}

static bool parserUptime(char *buf, Uptime *uptime) {
    
    if (isNull(buf)) return false;

    char* buffer = LineTrim(buf);
    GSList *uptime_split = split_cnt(buffer, ' ', 1);
    
    if (g_slist_length(uptime_split) == 2) {
        // stdlib.h
        // ┌──────────────────────────────────────────────────────────────────────────────┐
        // │ double atof(const char *)                                                    │
        // └──────────────────────────────────────────────────────────────────────────────┘
        double left = atof(g_slist_nth(uptime_split, 0)->data);
        double right = atof(g_slist_nth(uptime_split, 1)->data);

        uptime->day = ((int)left) / Day;
        uptime->hour = (((int)left) % Day) / Hour;
        uptime->min = (((int)left) % Hour) / Min;
        uptime->sec = ((int)left) % Min;
    }

    // g_slist_foreach(uptime_split, (GFunc)printf_iterator, "-->");
    GS_FREE_ALL_CLEAN(uptime_split)
    
    S_FREE(buffer);

    return true;
}

bool proc_uptime_to_buffer(Uptime *uptime, char *buffer) {
    if (uptime == NULL) return false;
    if (isNull(buffer)) return false;

    sprintf(buffer, "%dday %dh %dmin", 
                    uptime->day, 
                    uptime->hour, 
                    uptime->min);

    return true;;    
};


bool initUptime(Uptime *uptime) {
    char buffer[100] = {0};

    if (!FileExists(LINUX_OS_PROC_UPTIME)) return false;

    if (FileReadToBuffer(LINUX_OS_PROC_UPTIME, buffer, sizeof(buffer)) > 0) {
        return parserUptime(buffer, uptime);
    }

    return false;
}